<!-- components/PullToRefresh/index.vue -->
<template>
  <van-pull-refresh
    v-if="!props.disablePullRefresh"
    v-model="isRefreshing"
    @refresh="onRefresh"
  >
    <van-list
      v-model:loading="isLoading"
      :finished="props.finished"
      :finished-text="props.finishedText"
      :loading-text="props.loadingText"
      :error-text="props.errorText"
      :immediate-check="false"
      @load="onLoadMore"
    >
      <slot></slot>
    </van-list>
  </van-pull-refresh>

  <van-list
    v-else
    v-model:loading="isLoading"
    :finished="props.finished"
    :finished-text="props.finishedText"
    :loading-text="props.loadingText"
    :error-text="props.errorText"
    :immediate-check="false"
    @load="onLoadMore"
  >
    <slot></slot>
  </van-list>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import type { PullToRefreshProps, PullToRefreshEmits } from './types';

const props = withDefaults(defineProps<PullToRefreshProps>(), {
  disablePullRefresh: false,
  disableLoadMore: false,
  loadingText: '加载中...',
  finishedText: '没有更多了',
  errorText: '请求失败，点击重新加载',
  pageSize: 10
});

const emit = defineEmits<PullToRefreshEmits>();

// 当前页码
const currentPage = ref(1);

// 是否正在刷新
const isRefreshing = ref(false);

// 计算loading状态
const isLoading = computed({
  get: () => props.loading,
  set: (value) => emit('update:loading', value)
});

// 监听loading变化
watch(() => props.loading, (newVal) => {
  if (!newVal) {
    isRefreshing.value = false;
  }
});

// 下拉刷新
const onRefresh = () => {
  // 重置页码
  currentPage.value = 1;
  // 触发刷新事件
  emit('refresh');
};

// 上拉加载更多
const onLoadMore = () => {
  if (props.disableLoadMore || props.finished) return;

  // 触发加载更多事件，传递当前页码
  emit('load-more', currentPage.value);

  // 页码自增
  currentPage.value++;
};

// 暴露方法给父组件
defineExpose({
  // 手动触发刷新
  refresh: onRefresh,
  // 重置组件状态
  reset: () => {
    currentPage.value = 1;
    emit('update:finished', false);
  },
  // 获取当前页码
  getCurrentPage: () => currentPage.value
});
</script>
